package com.hui.servlet;

import com.hui.entity.Student;
import com.hui.service.StudentService;
import com.hui.util.DateUtil;
import com.hui.util.ServiceFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: 李昭辉
 * @Date: 2021/06/20/13:51
 * @Description:
 */
@WebServlet(name = "InsertAndUpdateServlet", urlPatterns = "/insertAndUpdate")
public class InsertAndUpdateServlet extends HttpServlet {
    private StudentService studentService = ServiceFactory.getStudentService();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String id = req.getParameter("id");
        String name = req.getParameter("name");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String email = req.getParameter("email");
        String desc = req.getParameter("desc");
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = resp.getWriter();
        // 如果有id那就是添加，没有的话就是修改
        if (id.equals("")) {
            Student student = new Student(name, gender, DateUtil.parse(birthday), email, desc);
            boolean b = studentService.insertStudent(student);
            if (b) {
                writer.write("<script>window.alert('添加成功!');window.location.href='pageStudent'</script>");
            } else {
                writer.write("<script>window.alert('添加失败!!!');window.location.href='pageStudent'</script>");
            }
        } else {
            Student student = new Student(Integer.parseInt(id), name, gender, DateUtil.parse(birthday), email, desc);
            boolean b = studentService.updateStudent(student);
            if (b) {
                writer.write("<script>window.alert('修改成功!');window.location.href='pageStudent'</script>");
            } else {
                writer.write("<script>window.alert('修改失败!!!');window.location.href='pageStudent'</script>");
            }
        }


    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
